/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { DEFAULT_IMMERSION_CALCULATION_FUNC, ImmersionRuleSet, ImmersionInfo, Size } from '../rule/ImmersionRuleSet';

/**
 * 自适应沉浸
 */
export class AdaptiveImmersion {
  private static instance: AdaptiveImmersion;
  private readonly tag: string = AdaptiveImmersion.name;

  private constructor() {
  }

  // 获取单例对象
  public static getInstance() {
    if (!AdaptiveImmersion.instance) {
      AdaptiveImmersion.instance = new AdaptiveImmersion();
    }
    return AdaptiveImmersion.instance;
  }

  // 获取沉浸信息
  public getImmersionInfo(videoSize: Size, windowSize: Size, statusBarHeight: number, bottomTabHeight: number): ImmersionInfo | undefined {
    // 计算视频宽高比
    try {
      const videoRatio: number = videoSize.width / videoSize.height;
      // 窗口尺寸
      const windowWidth = windowSize.width; // vp
      const windowHeight = windowSize.height; // vp
      const windowRatio = windowWidth / windowHeight;
      // 获取沉浸规则信息
      const adaptiveImmersionRule = ImmersionRuleSet.getInstance().getImmersionRule({
        videoRatio: videoRatio,
        windowWidth: windowWidth,
        windowRatio: windowRatio
      });

      // 获取沉浸规则（匹配成功或默认）
      const immersionCalculationFunc =
        adaptiveImmersionRule?.immersionCalculationFunc ?? DEFAULT_IMMERSION_CALCULATION_FUNC;
      return immersionCalculationFunc(videoSize, windowSize, bottomTabHeight, statusBarHeight);
    } catch (err: any) {
      console.error(this.tag, `Failed to get immersion info error, code: ${err.code}, error message: ${err.message}`);
      return undefined;
    }
  }
}